import Taro from "@tarojs/taro";
import { CustomRequest, baseUrl } from "./request";
import { changeToLogin } from "@/actions/login";
export const apiAuthenticateCheck = `/wechat/api/miniUser/getUserInfo`;
/**
 * 置业顾问分享的进来
 */
export const apiDoBind = `/wechat/api/employee/bindCustomer`;

export interface IAuthenticate {
  id: number;

  certificate: string;
  idCard: string;
  ownerInfo?: string;
  phone: string;
  realName: string;
  /**
   * 1：业主；2：非业主；3：渠道
   */
  type: number;
  projectName?: string;
  address?: string;
  reason?: string;

  /**
   * 0 审核中 -1 未通过  1通过
   */
  status: number;

  createTime: string;
  updateTime: string;
  projectId?: number;
}

const isFromCloud = (url: string) => {
  const reg = /^https.*/;
  if (reg.test(url)) {
    return true;
  } else {
    return false;
  }
};

export default class Auth {
  /**
   *
   * @param params 首页options 带的路由参数
   */
  static appCheckSessionKey(params?: object, callback?: () => void) {
    const That = this;
    //检测sessionkey
    Taro.checkSession({
      success: function () {
        //session_key 未过期，并且在本生命周期一直有效
        That.appWxLogin(params, callback); //重新登录
      },
      fail: function () {
        // Taro.clearStorageSync();
        // session_key 已经失效，需要重新执行登录流程
        That.appWxLogin(params); //重新登录
      }
    });
  }

  static appWxLogin(_params?: { scene?: string, telephone?: string }, callback?: () => void) {
    Taro.login({
      success: function (res) {
        if (res.code) {
          // console.log("jscode: ", res);
          Taro.setStorageSync("code", res.code);

          // 在专门的登录页面做处理
          return
        }
      },
      fail: function (err) {
        console.log("err", err);
      }
    });
  }

  static async appLogin() {
    // const dispatch = useDispatch()
    const res = await CustomRequest.post('/api/user/user/login', {}).catch(_e => { })
    // res token string
    if (res) {
      // 改变login true
      Taro.setStorageSync('token', res);
      // store.dispatch(changeToLogin())
      return true;
    } else {
      return false;
    }
  }

  static gotoLogin() {
    //清除缓存
    // 登录
    Taro.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          console.log(res);
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      }
    });
  }

  static checkPhoneAuth() {
    Taro.getStorage({
      key: "userInfo",
      success: function (res) {
        if (!res.data.phone) {
          // Taro.redirectTo({
          //   url: "/packages/package-user-login/user-login/index"
          // });
        }
      }
    });
  }

  static getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      // const scene = Taro.getStorageSync('userInfo').openId
      CustomRequest.post("/wechat/api/miniUser/authPhone", {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        wxToken: Taro.getStorageSync("token"),
        address: Taro.getStorageSync("city")
          ? Taro.getStorageSync("city")
          : "未授权",
        // scene
      })
        .then((res: any) => {
          if (res.id) {
            Taro.setStorageSync("userInfo", res);
            Taro.switchTab({
              url: "/pages/index/index"
            });
            // store.dispatch(openAvatarPermissionModal());
          }
        })
        .catch(_err => {
          Taro.showToast({
            title: "手机号授权失败,请稍后重试",
            icon: "none",
            duration: 2000
          });
        });
    }
  }


  static Upload(url: string, filePath: string, dir: string) {
    return new Promise((resolve, reject) => {
      console.log("filepath", filePath);
      if (isFromCloud(filePath)) {
        resolve(filePath);
        return
      }
      Taro.uploadFile({
        url: `${url}`,
        filePath,
        name: "file",
        formData: {
          dir
        },
        header: {
          "Content-Type": "multipart/form-data",
        },
        success: (res: any) => {
          const jsonData = JSON.parse(res.data);
          resolve(jsonData.retData);
        },
        fail: reject
      });
    });
  }

}
